package net.zoneland.zrdp.framework.web.exception;

import javax.servlet.http.HttpServletRequest;

import net.zoneland.zrdp.common.exception.BizException;
import net.zoneland.zrdp.common.exception.user.CaptchaException;
import net.zoneland.zrdp.common.exception.user.CaptchaExpireException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import net.zoneland.zrdp.common.constant.HttpStatus;
import net.zoneland.zrdp.common.core.domain.AjaxResult;
import net.zoneland.zrdp.common.exception.DemoModeException;
import net.zoneland.zrdp.common.exception.ServiceException;

import java.util.Objects;
import java.util.Optional;

/**
 * 全局异常处理器
 *
 * @author zonevue
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 权限校验异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    public AjaxResult handleAccessDeniedException(final AccessDeniedException e, final HttpServletRequest request) {
        final String requestURI = request.getRequestURI();
        LOGGER.error("统一异常处理：请求地址'{}',权限校验失败", requestURI, e);
        return AjaxResult.error(HttpStatus.FORBIDDEN, "没有权限，请联系管理员授权");
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public AjaxResult handleHttpRequestMethodNotSupported(final HttpRequestMethodNotSupportedException e,
            final HttpServletRequest request) {
        final String requestURI = request.getRequestURI();
        final String msg = String.format("请求地址'%s'不支持'%s'请求", requestURI, e.getMethod());
        LOGGER.error("统一异常处理：{}", msg, e);
        return AjaxResult.error(msg);
    }

    /**
     * 业务异常处理（包括 Service 和 Biz 异常）
     */
    @ExceptionHandler({ServiceException.class, BizException.class})
    public AjaxResult handleBusinessException(final RuntimeException e) {
        LOGGER.error("统一异常处理：", e);
        final Integer code = (e instanceof ServiceException) ? ((ServiceException) e).getCode() : ((BizException) e).getCode();
        // 自定义的异常
        final String message = StringUtils.defaultIfEmpty(e.getMessage(), "系统后台异常，请联系管理员");
        return Objects.nonNull(code) ? AjaxResult.error(code, message) : AjaxResult.error(message);
    }

    @ExceptionHandler({CaptchaException.class, CaptchaExpireException.class })
    public AjaxResult handleCaptchaException(final RuntimeException e) {
        LOGGER.error("统一异常处理：", e);
        // 自定义的异常
        final String message = StringUtils.defaultIfEmpty(e.getMessage(), "验证码不正确");
        return AjaxResult.error(message);
    }
    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public AjaxResult handleRuntimeException(final RuntimeException e, final HttpServletRequest request) {
        final String requestURI = request.getRequestURI();
        LOGGER.error("统一异常处理：请求地址'{}',发生未知异常.", requestURI, e);
        return AjaxResult.error("系统发生未知异常，请联系管理员");
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(final Exception e, final HttpServletRequest request) {
        final String requestURI = request.getRequestURI();
        LOGGER.error("统一异常处理：请求地址'{}',发生系统异常.", requestURI, e);
        return AjaxResult.error("系统发生异常，请联系管理员");
    }

    /**
     * 参数验证异常
     */
    @ExceptionHandler(BindException.class)
    public AjaxResult handleBindException(final BindException e) {
        LOGGER.error("统一异常处理：", e);
        // 或取第一个错误信息
        final String message = e.getAllErrors().get(0).getDefaultMessage();
        return AjaxResult.error(message);
    }

    /**
     * 参数验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object handleMethodArgumentNotValidException(final MethodArgumentNotValidException e) {
        LOGGER.error("统一异常处理：", e);
        final FieldError fieldError = e.getBindingResult().getFieldError();
        final String message = Optional.ofNullable(fieldError)
            .map(DefaultMessageSourceResolvable::getDefaultMessage)
            .orElse("参数校验不通过，请检查输入的内容。");
        return AjaxResult.error(message);
    }

    /**
     * 演示模式异常
     */
    @ExceptionHandler(DemoModeException.class)
    public AjaxResult handleDemoModeException(final DemoModeException e) {
        LOGGER.error("统一异常处理：", e);
        return AjaxResult.error("演示模式，不允许操作");
    }
}
